var currentList;
var jsonList;
var stepCount;

window.onload = function() {
	//localStorage["stepCount"] = "";
	//localStorage["tipList"] = "";
	//localStorage["jsonList"] = "";
	
	currentList = localStorage.tipList;
	jsonList = localStorage.jsonList;
	stepCount = localStorage.stepCount;
	
	if(stepCount != null && stepCount != "" && stepCount != 0 && typeof stepCount !== undefined) 
	{
		createTable();
	}	
	else
	{
		var table = document.getElementById("stepTable");
		var row = table.insertRow(1);
	}
	
	var temp = localStorage.testTip;
	if(temp == "true")
	{
		document.getElementById('four').scrollIntoView();
	}
};

/*
$(window).load(function(){
	log = function(str) {
		try { // prevent erroring
			if(typeof window.console !== undefined && typeof window.console.log !== undefined) {
				console.log(str);
			}
		} catch(e) {
			alert('[Debug] logging not possible.');
		}
	};
});
*/

document.addEventListener("mousedown", function (event) {
    var el = event.target;
	if(el.id == "myFind")
	{
		myFind_Click(el);
	}
	if(el.id == "addTip")
	{
		addTip_Click(el);
	}
	if(el.id == "deleteCell")
	{
		deleteCell_Click(el);
	}
	if(el.id == "testTip")
	{
		testTip(el);
	}
	if(el.id == "optionsLink")
	{
		optionsLink(el);
	}
}, true);

function optionsLink(el){
	var urls = chrome.extension.getURL("options.html"); //chrome.extension.getURL(&quot;/options.html&quot;);
	
	chrome.tabs.create({
        url: urls
	});
}

document.addEventListener("change", function (event) {
    var el = event.target;
	if(el.id == "selectBox")
	{
		var tex2 = el.options[el.selectedIndex].text;
		
		chrome.tabs.getSelected(null, function(tab) {
  	  		chrome.tabs.sendRequest(tab.id, {method: tex2, count: 2}, function (response) {});
		});
	}
}, false);

function myFind_Click(el){
	var e = document.getElementById("comboHTML");
  		var tex = e.options[e.selectedIndex].text;
  		
		
  		chrome.tabs.getSelected(null, function(tab) {
  	  		chrome.tabs.sendRequest(tab.id, {method: tex, count: 1}, function (response) {

				var temp = response.data.split(',');
				var combobox = document.createElement('select');
				combobox.id = "selectBox";
				
				for(i = 0; i < temp.length; i++)
				{
					var opt = document.createElement('option');
					opt.text = temp[i];
				    combobox.options.add(opt);
				}
				
				document.getElementById("fillDiv").innerHTML = "Select an element:";
				document.getElementById("fillDiv").appendChild(combobox);
				
				var mydiv = document.getElementById("formDiv");
				mydiv.style.display = "block"; //to show it
	  
   			});
  		});
}

function addTip_Click(el){
	var warn = document.getElementById("warningDiv");
	warn.innerText = "";
	
	var target = document.getElementById("selectBox").options[document.getElementById("selectBox").selectedIndex].text;
	localStorage["target"] = target;
	var title = document.getElementById("titleInput").value;
	localStorage["title"] = title;
	var description = document.getElementById("descInput").value;
	localStorage["description"] = description;
	var location = document.getElementById("locationInput").options[document.getElementById("locationInput").selectedIndex].value;
	localStorage["location"] = location;
	var tipLocation = document.getElementById("tipInput").options[document.getElementById("tipInput").selectedIndex].value;
	localStorage["tipLocation"] = tipLocation;
	var styleLocation = document.getElementById("styleInput").options[document.getElementById("styleInput").selectedIndex].value;
	localStorage["styleLocation"] = styleLocation;
	localStorage["testTip"] = "false";
	
	if(target ==  null || target == "none" || title == null ||  title == "" || description == null || description == "" || location == null || location == "" || tipLocation == null || tipLocation == "" || styleLocation == null || styleLocation == "")
	{
		warn.innerText = "WARNING: The form must be completed before proceeding.";
	}
	else
	{
		var obj = "";
		obj += "{ target: $('#" + target + "'), ";
		obj += "title: '" + title + "', ";
		obj += "content: '" + description + "', ";
		obj += "tipFocus: FOCUS." + location + ", ";
		obj += "elFocus: FOCUS." + tipLocation + ", ";
		obj += "style: STYLES." + styleLocation + " }";
	
		if (stepCount != "") {
			stepCount = parseInt(stepCount, 10);
		}
		else {
			stepCount = 0;
		}
			
		if(jsonList == null || jsonList == "")
		{
			jsonList = obj;
		}
		else
		{
			jsonList += ", " + obj;
		}
		if(currentList == null || currentList == "")
		{
			currentList = "1^" + target + "^" +title;
			stepCount = 1;
		}
		else
		{
			
			stepCount = stepCount + 1;
			currentList += "&" + stepCount.toString() + "^" + target + "^" +title;
		}
		
		createTable();
		
		localStorage["tipList"] = currentList;
        localStorage["jsonList"] = jsonList;
	    localStorage["stepCount"] = stepCount;
	}
}

function deleteCell_Click(el)
{
	var rowNumber = parseInt(el.name, 10);
	
	var newCurrentList = "";
	var parsedList = currentList.split("&");
	
	for(i = 0; i < parsedList.length; i++)
	{
		if (i != rowNumber) {
			if (newCurrentList == "") {
				newCurrentList = parsedList[i];
			}
			else {
				newCurrentList += "&" + parsedList[i];
			}
		}
	}
	
	var newJsonList = "";
	var parsedJson = jsonList.split("}, {");
	
	for(i = 0; i < parsedJson.length; i++)
	{
		if (i != rowNumber) {
			if (i == (parsedJson.length - 1) || (i == (parsedJson.length - 2) && (rowNumber == (parsedJson.length - 1)))) {
				newJsonList += parsedJson[i];
			}
			else {
				newJsonList += parsedJson[i] + "}, {";
			}
		}
	}
	
	var table = document.getElementById("stepTable");
	table.deleteRow(rowNumber + 1);
	
	localStorage["tipList"] = newCurrentList;
    localStorage["jsonList"] = newJsonList;
	localStorage["stepCount"] = ((parseInt(stepCount, 10)) - 1);
}

function createTable()
{
	deleteRows();
	
	var table = document.getElementById("stepTable");
	var rows = currentList.split("&");
	
	for(var i = 0; i < rows.length; i++)
	{
		var items = rows[i].split("^");
		
		var row = table.insertRow(i + 1);
		
		var cell1 = row.insertCell(0);
        cell1.innerHTML = items[0];
 
        var cell2 = row.insertCell(1);
        cell2.innerHTML = items[1];
		
		var cell3 = row.insertCell(2);
        cell3.innerHTML = items[2];
		
		var cell4 = row.insertCell(3);
		cell4.innerHTML = "<a href=\"#\" id='deleteCell' name='" + i + "'> X </a>";
	}
}

function deleteRows()
{
	var table = document.getElementById("stepTable");
    var rowCount = table.rows.length;
 
    for(var i=1; i<rowCount; i++) {
    	var row = table.rows[i];
        table.deleteRow(i);
                
		rowCount--;
        i--;
    }
        
}

function testTip(el)
{
	var target = document.getElementById("selectBox").options[document.getElementById("selectBox").selectedIndex].text;
	localStorage["target"] = target;
	var title = document.getElementById("titleInput").value;
	localStorage["title"] = title;
	var description = document.getElementById("descInput").value;
	localStorage["description"] = description;
	var location = document.getElementById("locationInput").options[document.getElementById("locationInput").selectedIndex].value;
	localStorage["location"] = location;
	var tipLocation = document.getElementById("tipInput").options[document.getElementById("tipInput").selectedIndex].value;
	localStorage["tipLocation"] = tipLocation;
	var styleLocation = document.getElementById("styleInput").options[document.getElementById("styleInput").selectedIndex].value;
	localStorage["styleLocation"] = styleLocation;
	localStorage["testTip"] = "true";
	
	var meth = target + "%" + title + "%" + description + "%" + location + "%" + tipLocation + "%" + styleLocation;
		
	chrome.tabs.getSelected(null, function(tab) {
			// Why is chrome requesting meth?
  	  		chrome.tabs.sendRequest(tab.id, {method: meth, count: 3}, function (response) {
				});
			});
}
